

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution
{
public:
    ListNode *detectCycle(ListNode *head)
    {
        if (!head) return nullptr;
        ListNode* fastptr = head;
        ListNode* slowptr = head;
        bool hasCycle = false;
        while (fastptr && slowptr && !hasCycle) {
            fastptr = fastptr->next;
            if (fastptr) fastptr = fastptr->next;
            slowptr = slowptr->next;
            if (fastptr && fastptr == slowptr) hasCycle = true;
        }
        if (!hasCycle) return nullptr;
        else {
            ListNode* ptr = head;
            while (ptr != slowptr) {
                ptr = ptr->next;
                slowptr = slowptr->next;
            }
            return ptr;
        }
    }
};